package com.jof.framework.hmc.core;

import java.util.HashMap;
import java.util.Map;

import org.hornetq.api.core.TransportConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * 支持集群模式的hornetq服務器配置
 * @author Jonathan
 * @see org.hornetq.api.core.TransportConfiguration
 * @see org.hornetq.api.jms.HornetQJMSClient
 * @see org.springframework.beans.factory.InitializingBean
 * @see org.springframework.beans.factory.FactoryBean
 */
public class TransportConfigurationFactoryBean implements FactoryBean<TransportConfiguration[]>,InitializingBean {
	private static final Logger LOGGER = LoggerFactory.getLogger(TransportConfigurationFactoryBean.class);
	private String serverAddress;
	private String className = "org.hornetq.core.remoting.impl.netty.NettyConnectorFactory";
	private TransportConfiguration[] transportConfigurations;
	
	public TransportConfiguration[] getObject() throws Exception {
		return this.transportConfigurations;
	}

	
	public Class<TransportConfiguration[]> getObjectType() {
		return TransportConfiguration[].class;
	}

	
	public boolean isSingleton() {
		return true;
	}

	public void setServerAddress(String serverAddress) {
		this.serverAddress = serverAddress;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(serverAddress,"必須指定hornetq服務器的ip和端口號！");
		LOGGER.info("加載hornetq服務器地址配置信息:{},using factory class:{}.",serverAddress,this.className);
		String[] arrays = serverAddress.split(",");
		Assert.notNull(arrays);
		Assert.notEmpty(arrays);
		this.transportConfigurations = new TransportConfiguration[arrays.length];
		int index = 0;
		for(String address : arrays){
			String[] addressGroup = address.split(":");
			Map<String, Object> parameters = new HashMap<String, Object>();
			parameters.put("host", addressGroup[0]);
			parameters.put("port", addressGroup[1]);
			this.transportConfigurations[index++] = new TransportConfiguration(this.className,parameters);
		}
	}
}
